<template>
  <div class="page-container out-container">
    <el-row :gutter="8">
      <el-col :span="4">
        <companyTree
          :loading="loading"
          :treeData="treeData"
          :title="'公司信息'"
          @node-click="nodeClick($event)"
        ></companyTree>
      </el-col>
      <el-col :span="20">
        <div class="in-container container">
          <!-- <AppSearchForm
            @submit="search"
            @reset="reset"
          >
            <el-form-item>
              <el-input
                v-model="query.title"
                clearable
                placeholder="请输入关键字"
              >
              </el-input>
            </el-form-item>
          </AppSearchForm> -->
          <div class="btn-box">
            <el-button
              type="default"
              icon="RefreshRight"
              @click="getTableData"
            >
            </el-button>
            <el-button
              type="primary"
              @click="openNew"
            >新增</el-button>
          </div>
          <el-table
            v-loading="tableData.option.loading"
            border
            row-key="id"
            ref="tableRef"
            class="table"
            header-row-class-name="tableHeader"
            :data="tableData.data"
          >
            <el-table-column
              prop="name"
              label="名称"
            />
            <el-table-column label="所属公司">
              <template #default="scope">
                {{ scope.row.company.name }}
              </template>
            </el-table-column>
            <el-table-column
              prop="sort"
              label="排序"
            >
              <template #default="scope">
                {{ scope.row.sort }}
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建日期"
            >
              <template #default="scope">
                {{ parseTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="225"
            >
              <template #default="scope">
                <el-button
                  @click="updateDept(scope.row)"
                  type="primary"
                >编辑</el-button>
                <el-button
              @click="editUserList(scope.row,scope.$index)"
              type="primary"
            >查看人员</el-button>
                <el-popconfirm
                  title="确定删除本条数据(包括下级)吗？"
                  @confirm="deleteDept(scope.row)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                    >删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <deptFormDialog
            ref="dialog"
            :companyData="treeData"
            v-model:model-data="formData"
            v-model:dialog-data="dialogData"
            @submit="submit"
            @cancel="cancel"
          >
          </deptFormDialog>
          <userFormDialog
      :deptId="DeptId"
      :currentName="currentName"
      v-model:userList="userList"
      v-model:dialog="userListDialog"
      @toChangeUserList="saveToUserList">
      ></userFormDialog>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import companyTree from "./components/companyTree.vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import { useTableOption } from "@/components/AppPageTable2";
import deptFormDialog from "./components/deptFormDialog.vue";
import userFormDialog from "./components/userFormDialog.vue";
import dayjs from "dayjs";
export default defineComponent({
  components: {
    companyTree,
    AppSearchForm,
    deptFormDialog,
    userFormDialog,
  },
  data() {
    return {
      loading: false,
      treeData: [],
      query: {
        title: "",
      },
      tableData: {
        data: [],
        option: useTableOption(),
      },
      dialogData: {
        show: false,
        title: "",
        btnLoading: false,
      },
      formData: {
        id: 0,
        companyId: "",
        name: "",
        parentId: "",
        director: "",
        telphone: "",
        email: "",
        description: "",
        sort: 1,
      },
      companyId: "",
      updateId: 0,
      deptData: [],
      //查看用户弹窗数据
      userListDialog:{
        show:false,
        btnLoading:false
      },
      //编辑角色授权用户时 保存该角色的授权用户数据
      userList:[],
      //编辑角色授权用户时 保存该角色的授权用户数据下标
      userListIndex:0,
      //编辑角色授权用户时 保存该角色部门ID
      DeptId:"",
      currentName:"",
    };
  },
  methods: {
    parseTime(date) {
      if (date) {
        return dayjs(date).format("YYYY-MM-DD");
      }
      return date;
    },
    // search() {
    //   this.getTableData();
    // },
    // reset() {
    //   this.query = {
    //     title: "",
    //   };
    //   this.getTableData();
    // },
    nodeClick(node) {
      this.companyId = node.id;
      this.getTableData();
    },
    initCompanyTree() {
      this.loading = true;
      this.$http
        .get("/api/company/buildTree", {
          KeyWords: "",
        })
        .then((res) => {
          this.treeData = res;
        })
        .finally(() => (this.loading = false));
    },
    updateDept(row) {
      this.dialogData.title = "修改部门";
      // let tableCopy = JSON.parse(JSON.stringify(this.tableData.data));
      // this.updateId = row.id;
      // this.deptFilter(tableCopy);
      // this.deptData = tableCopy;
      this.dialogData.show = true;
      if (row.parentId == "0") {
        row.parentId = "";
      }
      this.$nextTick(() => {
        let res = JSON.parse(JSON.stringify(row));
        this.formData = res;
      });
    },
    deleteDept(row) {
      this.$http
        .post("/api/department/delete", {
          idArray: [row.id],
        })
        .then((res) => {
          if (res.status) {
            this.getTableData();
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        });
    },
    getTableData() {
      this.tableData.option.loading = true;
      this.$http
        .get("/api/department/buildTree", {
          KeyWords: this.query.title,
          CompanyId: this.companyId,
        })
        .then((res) => {
          this.tableData.data = res;
        })
        .finally(() => (this.tableData.option.loading = false));
    },
    // validSubmit() {
    //   // if (
    //   //   !this.formData.id &&
    //   //   !this.formData.parentId &&
    //   //   this.tableData.data.length > 0
    //   // ) {
    //   //   this.$message.warning("请选择所属部门");
    //   // } else {
    //   this.submit();
    //   // }
    // },
    submit(deptData) {
      let url = "";
      if (this.formData.id) {
        url = "/api/department/edit";
      } else {
        url = "/api/department/create";
      }
      this.$refs.dialog.$refs.form.validate((valid) => {
        if (valid) {
          // if (
          //   !this.formData.id &&
          //   !this.formData.parentId &&
          //   this.tableData.data.length > 0 &&
          //   deptData.length > 0
          // ) {
          //   this.$message.warning("请选择所属部门");
          //   return
          // };
          this.dialogData.btnLoading = true;
          this.$http
            .post(url, this.formData)
            .then((res) => {
              if (res.status) {
                this.getTableData();
                this.$message.success(res.message);
                this.dialogData.show = false;
              } else {
                this.$message.error(res.message);
              }
            })
            .finally(() => (this.dialogData.btnLoading = false));
        }
      });
    },
    cancel() {
      this.dialogData.show = false;
    },
    openNew() {
      this.dialogData.show = true;
      this.dialogData.title = "新增部门";
    },
    // deptFilter(data) {
    //   for (let i = 0; i < data.length; i++) {
    //     if (data[i].id == this.updateId) {
    //       data.splice(i, 1);
    //     } else {
    //       if (data[i].children.length > 0) {
    //         this.deptFilter(data[i].children);
    //       }
    //     }
    //   }
    // },
    editUserList(row,index){
      this.currentName=row.name;
      this.userListIndex=index;
      this.DeptId=row.id;
      this.userList=row.users;
      this.userListDialog.show=true
    },
  },
  watch: {
    "dialogData.show"(newVal) {
      if (!newVal) {
        this.$nextTick(() => {
          this.formData.id = "";
          this.$refs["dialog"].$refs["form"].resetFields();
        });
      }
    },
  },
  mounted() {
    this.initCompanyTree();
    this.getTableData()
  },
});
</script>

<style lang="scss" scoped>
.out-container {
  background: #fff;

  :deep(.el-row) {
    height: 100%;
  }

  .container {
    display: flex;
    flex-direction: column;

    .btn-box {
      margin-bottom: 8px;
    }

    .table {
      flex: 1;

      :deep(.tableHeader) th {
        background-color: #f7f8fa !important;
      }
    }

    .page-component {
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
}
</style>
